import { init } from 'snabbdom/build/package/init.js'
import { h } from 'snabbdom/build/package/h.js'
import { classModule } from 'snabbdom/build/package/modules/class.js'
import { propsModule } from 'snabbdom/build/package/modules/props.js'
import { styleModule } from 'snabbdom/build/package/modules/style.js'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners.js'

var patch = init([classModule, propsModule, styleModule, eventListenersModule])

var vnode  //虚拟dom 
//初始数据

var originalData = [{
  index: 0,
  name: '剑圣',
  Desc: 'jiansheng123'
},
{
  index: 1,
  name: '蛮王',
  Desc: '五秒真男人'
}
  , {
  index: 2,
  name: '赵信',
  Desc: '大家好我是菊花信'
}
  , {
  index: 3,
  name: '寒冰',
  Desc: '蛮王老婆,刮痧之王'
},
{
  index: 4,
  name: '腕豪',
  Desc: '人称峡谷敬夫'
}]
var data = [
  originalData[0],
  originalData[1],
  originalData[2],
  originalData[3],
  originalData[4]
]
var nextKey = 4
var sortBy = 'index'
function changeSort(prop) {
  sortBy = prop
  data.sort((a, b) => {
    if (a[prop] > b[prop]) {
      return 1
    }
    if (a[prop] < b[prop]) {
      return -1
    }
    return 0
  })
  vnode = patch(vnode, view(data))
}
function add() {
  let n = originalData[Math.floor(Math.random() * 5)]
  data = [{ index: nextKey++, name: n.name, Desc: n.Desc }].concat(data)
  vnode = patch(vnode, view(data))
}
function view(data) {
  return h(
    'div',
    [
      h('h1', '峡谷打工人名单'),
      h('div', [
        h('a.btn.add', { on: { click: add } }, 'Add'),
        'Sort by: ',
        h('span.btn-group', [h('a', { class: { active: sortBy === 'index' }, on: { click: () => changeSort('index') } }, 'index'),
        h('a', { class: { active: sortBy === 'name', margin: true }, on: { click: () => changeSort('name') } }, 'name'),
        h('a', { class: { active: sortBy === 'desc' }, on: { click: () => changeSort('Desc') } }, 'Desc')])

      ]),
      h('div.list', { style: { height: 1000 + 'px' } }, data.map(heroView)),
    ]
  )
}
function heroView(hero) {
  return h('div.row', {
    key: hero.rank,
    style: {
      opacity: '1',
      // transform: 'translate(-200px)',
      // delayed: { transform: `translateY(${movie.offset}px)`, opacity: '1' },
      // remove: { opacity: '0', transform: `translateY(${movie.offset}px) translateX(200px)` }
    },
    // hook: { insert: (vnode) => { movie.elmHeight = vnode.elm.offsetHeight } },
  }, [
    h('div', { style: { fontWeight: 'bold' } }, hero.index),
    h('div', hero.name),
    h('div', hero.Desc),
    h('div.btn.rm-btn', { on: { click: () => { remove(hero) } } }, 'x'),
  ])
}
function remove(hero) {
  data = data.filter((m) => {
    return m !== hero
  })
  vnode = patch(vnode, view(data))
}
window.addEventListener('DOMContentLoaded', () => {
  let app = document.querySelector('#app')
  vnode = patch(app, view(data))

})